package dk.sdu.flexibus.persistence;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class Persister {

	static int readInt(SharedPreferences preferences, int id, String field, int defaultValue){
		int intResult = preferences.getInt(""+id+field, Integer.MIN_VALUE);
		if(intResult == Integer.MIN_VALUE){
			return defaultValue;
		}
		return intResult;
	}

	static void writeInt(SharedPreferences preferences, int id, String field, int value) {
		if(value == Integer.MIN_VALUE) return;
		Editor e = preferences.edit();
		e.putInt(""+id+field, value);
		e.commit();
	}

	static String readString(SharedPreferences preferences, int id, String field, String defaultValue){
		return preferences.getString(""+id+field, defaultValue);
	}

	static void writeString(SharedPreferences preferences, int id, String field, String value) {
		if(value == null) return;
		Editor e = preferences.edit();
		e.putString(""+id+field, value);
		e.commit();
	}

	static void writeLong(SharedPreferences preferences, int id, String field, long value) {
		if(value == Long.MIN_VALUE) return;
		Editor e = preferences.edit();
		e.putLong(""+id+field, value);
		e.commit();
	}

	static Calendar readCalendar(SharedPreferences preferences, int id, String field, Calendar defaultValue){
		long resultLong = TransportFactory.readLong(preferences, id, field, Long.MIN_VALUE);
		if(resultLong != Long.MIN_VALUE){
			Calendar result = new GregorianCalendar();
			result.setTimeInMillis(resultLong);
			return result;
		} else {
			return defaultValue;
		}
	}

	static void writeCalendar(SharedPreferences preferences, int id, String field, Calendar value) {
		if(value == null) return;
		writeLong(preferences, id, field, value.getTimeInMillis());
	}

	public static void clearStore(SharedPreferences preferences) {
		Editor e = preferences.edit();
		e.clear();
		e.commit();
	}

	public static final String PREFS_FILE_NAME = "MyPrefsFile";

	public static int getMaxId(SharedPreferences preferences, String key){
		return preferences.getInt(key, 0)-1;
	}

	static int getNextId(SharedPreferences preferences, String key){
		int result = preferences.getInt(key, 0);
		Editor e = preferences.edit();
		e.putInt(key, result+1);
		e.commit();
		return result;
	}

}
